/*********************************************************
          File Name:pisces_log.c
          Author: Abby Cin
          Mail: abbytsing@gmail.com
          Created Time: Fri 24 Apr 2015 11:12:14 PM CST
**********************************************************/

#include "pisces_log.h"
#include "global.h"
#include <sys/stat.h>

int pisces_open_log()
{
    FILE *fp = NULL;

    if (access(LOG_FILE_PATH, F_OK) == 0)
        return LOG_SUCCESS;
    else {
        if ((fp = fopen(LOG_FILE_PATH, "w")) == NULL)
            return LOG_FAILED;
        fclose(fp);
    }
    chmod(LOG_FILE_PATH, 00666);
    return LOG_SUCCESS;
}

int pisces_log(int log, const char *fmt, ...)
{
    FILE *fp = NULL;
    va_list arg;
    time_t tm;
    char *s = NULL;
    char buf[25];

    fp = fopen(LOG_FILE_PATH, "a+");
    if (fp == NULL)
        return LOG_FAILED;

    va_start(arg, fmt);

    switch (log) {
    case P_LOG_IFO:
        s = "LOG_IFO";
        break;
    case P_LOG_ERR:
        s = "LOG_ERR";
        break;
    case P_LOG_ALT:
        s = "LOG_ALT";
        break;
    }

    tm = time(NULL);
    ctime_r(&tm, buf);
    buf[sizeof(buf) - 1] = '\0';
    fprintf(fp, "[TIME]%s [%s] PID=%d [MSG] :", buf, s, getpid());
    vfprintf(fp, fmt, arg);
    fprintf(fp, "\n");
    va_end(arg);
    fclose(fp);
    return LOG_SUCCESS;
}
